<template>
  <el-table ref="multipleTableRef" :data="list" stripe :height="tabH" :style="{ width: '100%', height: tabH }" @selection-change="handleSelectionChange" class="table-box" header-row-class-name="table_header_title">
    <el-table-column type="selection" width="55" fixed="left" />
    <el-table-column label="标题" min-width="200">
      <template #default="scope">
        <div class="cusInfo">
          <div class="name">{{ scope.row.activity_name }}</div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="二维码" width="80">
      <template #default="scope">
        <div class="cusInfo">
          <el-image :preview-src-list="[scope.row.qr_code_link]" :preview-teleported="true" :src="scope.row.qr_code_link" fit="cover" class="avatar">
            <template #error>
              <div class="image-slot">
                <el-icon>
                  <icon-picture />
                </el-icon>
              </div>
            </template>
          </el-image>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="使用成员" width="220px">
      <template #default="scope">
        <div>
          <span v-if="scope.row.formal.length">
            <span style="color: #ff6b00">{{ scope.row.formal[0] }}</span
            >等
            <span v-if="scope.row.formal.length">{{ scope.row.formal.length }}个成员</span>
          </span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="备用成员" width="220px">
      <template #default="scope">
        <div>
          <!-- <span v-for="e in scope.row.work_user.work_department" :key="e.id">{{
          e.name
        }}</span> -->
          <span v-if="scope.row.reserve.length">
            <span style="color: #ff6b00">{{ scope.row.reserve[0] }}</span
            >等
            <span v-if="scope.row.reserve.length">{{ scope.row.reserve.length }}个成员</span>
          </span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="扫码添加次数" width="200px">
      <template #default="scope">
        <div>
          <span>{{ scope.row.scan_num }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="所属分组" width="140px">
      <template #default="scope">
        <div>
          <span>{{ scope.row.group_name }}</span>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="创建人" width="130px">
      <template #default="scope">
        <div class="cusInfo">
          <div class="name">{{ scope.row.created_user }}</div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="创建时间" width="180px">
      <template #default="scope">
        <div class="cusInfo">
          <div class="name">{{ scope.row.created_at }}</div>
        </div>
      </template>
    </el-table-column>
    <el-table-column label="状态" width="100">
      <template #default="scope">
        <div v-if="scope.row.activity_status === 1">未开始</div>
        <div v-if="scope.row.activity_status === 2">进行中</div>
        <div v-if="scope.row.activity_status === 3">已结束</div>
        <div v-if="scope.row.activity_status === 4">提前结束</div>
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" width="300">
      <template #default="scope">
        <div class="handle">
          <ElButton  size="small" v-show="scope.row.activity_status !== 1" @click="check(scope.row)" v-auth="'CUST_CODE'"> 客户明细 </ElButton>
          <ElButton size="small" v-show="scope.row.activity_status == 1 || scope.row.activity_status == 2 || scope.row.activity_status == 4" @click="look(scope.row)" v-auth="'LOOK_CODE'"> 查看 </ElButton>
          <ElButton  size="small" v-show="scope.row.activity_status == 2 || scope.row.activity_status == 1" @click="edit(scope.row)" v-auth="'EDIT_CODE'"> 编辑 </ElButton>
          <ElButton  size="small" v-show="scope.row.activity_status == 1"  @click="start(scope.row)" v-auth="'END_CODE'"> 开始 </ElButton>
          <ElButton  size="small" v-show="!scope.row.activity_status == 4 || scope.row.activity_status == 2" @click="finish(scope.row)" v-auth="'END_CODE'"> 结束 </ElButton>
          <ElButton size="small" @click="downloads(scope.row)" v-show="scope.row.activity_status != 4" v-auth="'DOW_CODE'">下载</ElButton>
          <ElButton size="small" @click="goStat(scope.row)" v-show="scope.row.activity_status != 1" v-auth="'CHANNEL_STAT'">统计</ElButton>
          <ElButton size="small" @click="del(scope.row)" v-auth="'DEL_CODE'">删除</ElButton>
        </div>
      </template>
    </el-table-column>
    <template #empty>
      <img class="emty_img" src="@/assets/noData.png" alt="" />
      <div class="emty_title">暂无数据</div>
    </template>
  </el-table>
  <!-- 侧边栏 -->
  <el-drawer size="47%" v-model="showDrawer" :direction="direction" class="drawer">
    <template #title>
      <h4 class="drawerTitle">客户明细</h4>
    </template>
    <template #default>
      <el-form :model="searchKeyWord">
        <el-form-item label="成员搜索" class="searchItem" v-if="false">
          <el-input v-show="false" v-model="searchKeyWord" placeholder="请输入成员名称" />
          <el-input v-model="searchKeyWord" placeholder="请输入成员名称" />
        </el-form-item>
      </el-form>
      <el-table max-height="550" ref="multipleTableRef" :data="filterData" stripe style="width: 100% height: 200px" @selection-change="handleSelectionChange" class="tableData" :header-cell-style="{ background: '#F9F9F9', color: '#33302D' }">
        <el-table-column label="客户信息">
          <template #default="scope">
            <div class="cusInfo">
              <el-image style="width: 36px; height: 36px" :src="scope.row.cust_avatar" fit="cover" class="avatar">
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <icon-picture />
                    </el-icon>
                  </div>
                </template>
              </el-image>
              <div class="cusName">{{ scope.row.cust_name }}</div
              ><span v-if="scope.row.cust_nickname" class="cust_border">|</span>
              <div class="cust_nickname" v-if="scope.row.cust_nickname">{{ scope.row.cust_nickname }}</div>
              <div class="cust_remark" v-if="scope.row.cust_remark">
                <span class="cust_remark_text">( {{ scope.row.cust_remark }}</span> <span>)</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="添加成员" width="150">
          <template #default="scope">
            <div class="cusInfo">
              <div class="name">{{ scope.row.user_name }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="客户状态">
          <template #default="scope">
            <div>{{ scope.row.cust_status }}</div>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" width="150">
          <template #default="scope">
            <div>
              <p>{{ scope.row.created_at }}</p>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <div style="height: 500px" class="emty">
            <img class="emty_img" src="@/assets/noData.png" alt="" />
            <div class="emty_title">{{ filterData.length || '暂无数据' }}</div>
          </div>
        </template>
      </el-table>
      <el-pagination
        v-model:currentPage="cusPage.page"
        :page-sizes="[15, 25, 50, 100]"
        v-model:page-size="cusPage.page_size"
        background
        layout="total, prev, pager, next, sizes"
        :total="cusPage.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </template>
  </el-drawer>
  <Dialog :appDialog="appDialog">
    <div class="msg">{{ message }}</div>
  </Dialog>
  <ZWPagination @submit="page" ref="PaginationRef"></ZWPagination>
</template>

<script lang="ts" setup>
  import { computed, reactive, ref, watch, onMounted } from 'vue'
  import { Picture as IconPicture } from '@element-plus/icons-vue'
  import { ElMessage, ElTable } from 'element-plus'
  import router from '@/router'
  import { useRoute } from 'vue-router'
  import ZWPagination from '@/components/ZWPagination.vue'
  import Dialog from '@/components/Dialog.vue'
  import Update from './Update.vue'
  import { getCodeList, cusDetails } from '@/api/smartMarketing/drainage/channelCode/index'
  import { beginningOrEnd, batchDel, lookCode, batchDownLoad } from '@/api/smartMarketing/drainage/channelCode/index'
  import { useStore } from '@/store'
  import { getSetionId, tableH, reSize } from '@/utils/utils'
  import bus from '@/utils/bus'
  const store = useStore()
  const route = useRoute()
  const multipleTableRef = ref<InstanceType<typeof ElTable>>()
  const emit = defineEmits(['refreshGroup'])

  const showDrawer = ref(false) // 显示右边侧边来
  const isEdit = ref(false) // 是否为编辑
  const title = ref() // 弹框标题
  const message = ref() //弹框提示内容
  const endId = ref() // 结束 id
  const isDel = ref(false) // 是否为删除
  const delId = ref([])
  const searchKeyWord = ref()
  const groupId = ref()
  const defaultGroupId = Number(route.params?.group_id)

  const params = ref({
    page: '1',
    page_size: '15',
    group_id: defaultGroupId || 0,
    name: '',
    created_uid: '',
    activity_status: '',
    create_time: []
  })
  const pageData = ref({
    activity_id: '',
    page: 1,
    page_size: 15
  })
  const cusPage = reactive({
    page: 1,
    page_size: 15,
    total: ''
  })
  const filterData = ref()
  const customer = ref([]) // 选中的删除客户
  const handleSelectionChange = (val: any) => {
    const arr: any = []
    val.map((item: any) => {
      arr.push(item.id)
    })
    customer.value = arr
    bus.emit('isCheck', arr)
  }
  const tableData = ref(null)
  const list = ref([])
  const tabH = ref('400px')
  const getTableH = () => {
    tabH.value = tableH('.table-box')
  }
  const send = (val?: any) => {
    if (val) {
      params.value.name = val.title ? val.title : ''
      params.value.created_uid = val.user_id ? val.user_id : ''
      params.value.group_id = val.id ? val.id : '0'
      groupId.value = val.id
      params.value.create_time = val.create_time ? val.create_time : ''
      params.value.activity_status = val.reason ? val.reason : ''
    }
    getList()
  }
  // 获取列表数据
  const getList = (val?: any) => {
    if (val) {
      params.value.name = val.title ? val.title : ''
      params.value.created_uid = val.user_id ? val.user_id : ''
      params.value.create_time = val.create_time ? val.create_time : ''
      params.value.activity_status = val.reason ? val.reason : ''
    }
    getCodeList(params.value).then((data: any) => {
      list.value = data.data
      filterData.value = data.data
      store.dispatch('pageTotal', data.total)
    })
  }
  const getDelList = (data: any) => {
    cusDetails(data).then((res: any) => {
      filterData.value = res.list
      cusPage.total = res.total
    })
  }
  // 客户明细
  const check = (data: any) => {
    showDrawer.value = true
    pageData.value.activity_id = data.id
    getDelList(pageData.value)
  }
  const handleSizeChange = (val: number) => {
    pageData.value.page_size = val
    getDelList(pageData.value)
  }
  const handleCurrentChange = (val: number) => {
    pageData.value.page = val
    getDelList(pageData.value)
  }
  // 查看
  const look = (data: any) => {
    lookCode({ activity_id: data.id }).then((res: any) => {
      store.dispatch('groupCode/lookData', res)
      router.push({
        path: '/smartMarketing/drainage/channelCode/newGroupCode',
        query: { type: 'look', id: data.id }
      })
    })
  }
  //编辑
  const edit = (data: any) => {
    isEdit.value = true
    router.push({
      path: '/smartMarketing/drainage/channelCode/newGroupCode',
      query: { type: 'edit', id: data.id }
    })
  }
  // 开始
  const start = (data: any) => {
    const result = { activity_id: data.id, status: 1 }
    beginningOrEnd(result)
      .then((res: any) => {
        getList(params)
      })
      .catch((e: any) => {
        console.log(e, '错误')
      })
  }
  // 结束
  const finish = (data: any) => {
    endId.value = data.id
    title.value = '结束'
    message.value = '结束活码不可再次扫码添加'
    appDialog.visible = true
  }
  const download = (href: any, name: any) => {
    let eleLink = document.createElement('a')
    eleLink.download = name
    eleLink.href = href
    eleLink.click()
    eleLink.remove()
  }
  const downloadByBlob = (url: any, name: any) => {
    let image = new Image()
    image.setAttribute('crossOrigin', 'anonymous')
    image.src = url
    image.onload = () => {
      let canvas = document.createElement('canvas')
      canvas.width = image.width
      canvas.height = image.height
      let ctx = canvas.getContext('2d')
      ctx.drawImage(image, 0, 0, image.width, image.height)
      canvas.toBlob((blob) => {
        let url = URL.createObjectURL(blob)
        download(url, name)
        // 用完释放URL对象
        URL.revokeObjectURL(url)
      })
    }
  }
  // 下载
  const downloads = (data: any) => {
    const params = {
      activity_id: []
    }
    params.activity_id.push(data.id)
    batchDownLoad(params)
      .then((res: any) => {
        downloadByBlob(res.url.url, res.url.name)
      })
      .catch((e: any) => {
        console.log(e)
      })
  }
  // 统计
  const goStat = (row: any) => {
    router.push({
      path: '/smartMarketing/drainage/channelCode/stat',
      query: { id: row.id }
    })
  }
  // 删除
  const del = (data: any) => {
    isDel.value = true
    title.value = '删除'
    message.value = '确认要删除吗？'
    appDialog.visible = true
    delId.value.push(data.id)
  }
  // 分页信息
  const page = (data: any) => {
    params.value.page = data.page
    params.value.page_size = data.page_size
    getList()
  }
  // 弹框取消
  const cancelHandel = () => {
    appDialog.visible = false
  }
  // 弹框确认按钮
  const submitHandel = () => {
    if (!isDel.value) {
      const result = { activity_id: endId.value, status: 2 }
      // params.value.group_id = groupId.value
      beginningOrEnd(result)
        .then((res: any) => {
          appDialog.visible = false
          getList(params.value)
        })
        .catch((e: any) => {
          console.log(e, '错误')
        })
    } else {
      const params = {
        activity_id: delId.value
      }
      batchDel(params)
        .then((res: any) => {
          getList(params)
          emit('refreshGroup')
          appDialog.visible = false
          ElMessage.success('删除成功')
        })
        .catch((err: any) => {
          ElMessage.success('删除失败')
        })
    }
  }
  // 弹框配置项
  const appDialog = reactive({
    visible: false,
    title: title,
    width: '460px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '确定',
    isInit: false, //是否重置
    isChooseDisabled: false, //重新打开传递进来的数据是否重置
    chooseArr: [] // 传递进来选中的数据
  })
  const refresh = () => {
    getList(params)
  }
  watch(
    () => searchKeyWord.value,
    () => {
      filterData.value = list.value.filter((item: any) => {
        // store.dispatch("pageTotal", filterData.value.total);
        return item.created_user.indexOf(searchKeyWord.value) != -1
      })
    }
  )

  onMounted(() => {
    send()
    getTableH()
    reSize(getTableH)
  })
  defineExpose({
    getList,
    send,
    groupId,
    refresh,
    customer,
    params,
    getTableH
  })
</script>
<style scoped lang="scss">
  .tableData {
    background: #ffffff;
    // box-sizing: border-box;
    border: 1px solid #eaeaea;

    .cusInfo {
      display: flex;
      align-items: center;

      .cusName {
        margin-left: 5px;
      }
      .cust_border {
        margin: 0 5px;
      }

      .cust_nickname {
        max-width: 70px;
        text-overflow: ellipsis;
        overflow: hidden;
        white-space: nowrap;
        margin-right: 5px;
      }

      .cust_remark {
        &_text {
          max-width: 50px;
          text-overflow: ellipsis;
          overflow: hidden;
          white-space: nowrap;
        }
      }

      .avatar {
        width: 60px;
        height: 60px;
        border-radius: 4px;

        .image-slot {
          .el-icon {
            font-size: 36px;
          }
        }
      }

      .name {
        margin: 0 5px;
      }

      .channel {
        font-size: 14px;
        color: #60b900;
      }

      .sex {
        width: 18px;
        height: 18px;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

  

    .tagList {
      display: flex;
      align-items: center;
      flex-wrap: wrap;

      .tag_item {
        padding: 4px;
        color: #ff6b00;
        margin: 0 10px 10px 0;
        border-radius: 2px;
        border: 1px solid #ffc69e;

        &:nth-child(n + 6) {
          display: none;
        }
      }
    }

    .emty {
      margin-top: 200px;
      // display: flex;
      // flex-direction: column;
    }

    .emty_img {
      transform: translateX(15%);
    }

    .emty_title {
      margin-top: -50px;
    }
  }

  .conceal {
    display: flex;
    flex-wrap: wrap;

    &_tag_item {
      padding: 4px;
      color: #ff6b00;
      margin: 0 10px 10px 0;
      border-radius: 2px;
      border: 1px solid #ffc69e;
    }
  }

  :deep .searchItem {
    padding-bottom: 19px;
    border-bottom: 1px solid #eaeaea;
  }

  .msg {
    text-align: center;
    padding: 50px 0;
  }
  :deep .el-drawer.rtl {
    width: 40%;
  }
  .cust_border {
    margin: -1px 2px 0 0;
  }
    .handle {
      display: flex;
      flex-wrap: wrap;
      font-size: 14px;

      .el-button {
        cursor: pointer;
        display: inline-block;
        vertical-align: middle; 
        width: 80px;
        height: 24px;
        padding: 0;
        margin: 0 4px 8px;
        border: 1px solid #eaeaea;
        border-radius: 2px;
        text-align: center;
        background: #fff;
      }
    }
</style>
